package cn.shop.utils;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import cn.shop.core.bean.UserInfo;

public class FrontLoginFilter implements Filter {

	/**
	 * Default constructor.
	 */
	public FrontLoginFilter() {
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see javax.servlet.Filter#destroy()
	 */
	public void destroy() {
		// TODO Auto-generated method stub
	}

	/**
	 * @see javax.servlet.Filter#doFilter(javax.servlet.ServletRequest, javax.servlet.ServletResponse, javax.servlet.FilterChain)
	 */
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;
		HttpSession session = req.getSession();

		UserInfo user = (UserInfo) session.getAttribute("user");

		String url = req.getRequestURI();
		System.out.println(url);

		if (!url.contains("/admin") ) {
			chain.doFilter(request, response);
		}else if(url.contains("/admin") && user != null){
			chain.doFilter(request, response);
		} else {
			req.getRequestDispatcher("/WEB-INF/front_page/login.jsp").forward(request, response);
		}

	}

	/**
	 * @see javax.servlet.Filter#init(javax.servlet.FilterConfig)
	 */
	public void init(FilterConfig fConfig) throws ServletException {
		// TODO Auto-generated method stub
	}

}
